package com.itheima.c_case;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LastTimeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//处理响应乱码
		response.setContentType("text/html;charset=utf-8");
		//获取所有的cookie数组
		Cookie[] cookies = request.getCookies();
		//从cookie数组中查找含有lastTime的cookie
		Cookie co = null;
		if(cookies!=null){
			//查找cookie
			for(Cookie cookie:cookies){
				//哪个cookie含有lastTime
				if("lastTime".equals(cookie.getName())){
					co=cookie;
				}
			}
		}
		//判断是否存在cookie
		if(co!=null){
			response.getWriter().print("您上次的访问时间为："+co.getValue());
		}else{
			response.getWriter().print("欢迎访问");
		}
		//获取当前的时间
		DateFormat df = DateFormat.getDateTimeInstance();
		String format = df.format(new Date());
		//把当前时间放入cookie中
		Cookie cookie = new Cookie("lastTime", format);
		//设置cookie的存活时间
		cookie.setMaxAge(3600);
		//写回到浏览器
		response.addCookie(cookie);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}